package nathizm;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import com.google.gdata.client.blogger.BloggerService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Entry;
import com.google.gdata.data.HtmlTextConstruct;
import com.google.gdata.data.Person;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.util.ServiceException;

public class PostNewEntry extends Blogger {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		File dir = new File(
				System.getProperty(Global.ENTRY_FOLDER_KEY) + "\\new");
		File[] files = dir.listFiles();

	    // Ask the service to insert the new entry
	    try 
	    {
		    URL postUrl = new URL(FEED_URI + POSTS_FEED_URI_SUFFIX);
			BloggerService myService = getService();
			for (File file : files) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						new FileInputStream(file)));
				StringBuffer sb = new StringBuffer();
				int c;
				while ((c = br.read()) != -1) {
					sb.append((char) c);
				}
				
				String title = file.toString().split("[_.]")[1];
				
			    // Create the entry to insert
			    Entry myEntry = new Entry();
			    myEntry.setTitle(new PlainTextConstruct(title));

				HtmlTextConstruct html = new HtmlTextConstruct();
				html.setHtml(sb.toString());
			    myEntry.setContent(html);
			    Person author = new Person(AUTHOR_NAME, null, System.getProperty(Global.USER_ID_KEY));
			    myEntry.getAuthors().add(author);
			    myEntry.setDraft(true);
			    
			    String pubTime = file.getName().split("_")[0];
			    
			    String timeBuf = 
			    		pubTime.substring(0,4) + "-" + pubTime.substring(4, 6) + "-" + pubTime.substring(6, 8) + "T"
			    		+ pubTime.substring(8, 10) + ":" + pubTime.substring(10, 12) + ":" + pubTime.substring(12, 14) 
			    		+ ".000+09:00";
			    myEntry.setPublished(DateTime.parseDateTime(timeBuf));

			    Entry newEntry = myService.insert(postUrl, myEntry);
			    outputFile(newEntry);
			}
			
		} catch (ServiceException se) {
			se.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	    
	}

}
